package com.szh.mysobproject.ui.fragment.user.media

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import com.hjq.umeng.Platform
import com.hjq.umeng.UmengShare
import com.szh.mysobproject.R
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.app.AppFragment
import com.szh.mysobproject.databinding.ShareDialogBinding
import com.szh.mysobproject.databinding.UserArticleListFragmentBinding
import com.szh.mysobproject.model.UserArticle
import com.szh.mysobproject.other.IntentKey
import com.szh.mysobproject.ui.activity.BrowserActivity
import com.szh.mysobproject.ui.activity.ImagePreviewActivity
import com.szh.mysobproject.ui.adapter.AdapterDelegate
import com.szh.mysobproject.ui.adapter.UserArticleAdapter
import com.szh.mysobproject.ui.dialog.ShareDialog
import com.szh.mysobproject.util.SUNNY_BEACH_ARTICLE_URL_PRE
import com.szh.mysobproject.util.SimpleLinearSpaceItemDecoration
import com.szh.mysobproject.util.dp
import com.szh.mysobproject.util.loadStateListener
import com.szh.mysobproject.viewmodel.ArticleViewModel
import com.szh.mysobproject.widget.StatusLayout
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import kotlinx.coroutines.flow.collectLatest

/**
 * @author : create by  szh
 * @date : 2022/7/7 16:08
 * @desc :用户文章列表 Fragment
 */

class UserArticleListFragment : AppFragment<AppActivity>(), StatusAction {

    private val mBinding by viewBinding<UserArticleListFragmentBinding>()
    private val mAdapterDelegate = AdapterDelegate()
    private val mArticleViewModel by activityViewModels<ArticleViewModel>()
    private val mUserArticleAdapter = UserArticleAdapter(mAdapterDelegate)
    private val loadStateListener = loadStateListener(mUserArticleAdapter) {
        mBinding.refreshLayout.finishRefresh()
    }

    override fun getLayoutId(): Int = R.layout.user_article_list_fragment

    override fun initView() {
        mBinding.rc.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mUserArticleAdapter
            addItemDecoration(SimpleLinearSpaceItemDecoration(4.dp))
        }
    }

    override fun initData() {
        val userId = arguments?.getString(IntentKey.ID, "") ?: ""
        loadUserArticleList(userId)
    }

    private fun loadUserArticleList(userId: String) {
        viewLifecycleOwner.lifecycleScope.launchWhenCreated {
            mArticleViewModel.getUserArticleList(userId).collectLatest {
                mUserArticleAdapter.submitData(it)
            }
        }
    }

    override fun initEvent() {
        mBinding.refreshLayout.setOnRefreshListener {
            mUserArticleAdapter.refresh()
        }
        // 需要在 View 销毁的时候移除 listener
        mUserArticleAdapter.addLoadStateListener(loadStateListener)
        mAdapterDelegate.setOnItemClickListener { _, position ->
            val item = mUserArticleAdapter.snapshot()[position] ?: return@setOnItemClickListener
            val url = "$SUNNY_BEACH_ARTICLE_URL_PRE${item.id}"
            BrowserActivity.start(requireContext(), url)
        }
        //查看图片
        mUserArticleAdapter.setOnNineGridClickListener { source, index ->
            ImagePreviewActivity.start(requireContext(), source, index)
        }
        //分享 or 点赞
        mUserArticleAdapter.setOnMenuItemClickListener { view, item, position ->
            when (view.id) {
                R.id.ll_share -> shareArticle(item)
//                //TODO:点赞
//                R.id.ll_great ->
            }
        }
    }

    private fun shareArticle(item: UserArticle.UserArticleItem) {
        val articleId = item.id
        val content = UMWeb(SUNNY_BEACH_ARTICLE_URL_PRE + articleId)
        content.title = item.title
        content.setThumb(UMImage(requireContext(), R.mipmap.launcher_ic))
        content.description = getString(R.string.app_name)
        //分享
        ShareDialog.Builder(requireActivity())
            .setShareLink(content)
            .setListener(object : UmengShare.OnShareListener {

                override fun onSucceed(platform: Platform?) {
                    toast("分享成功")
                }

                override fun onError(platform: Platform?, t: Throwable) {
                    toast(t.message)
                }

                override fun onCancel(platform: Platform?) {
                    toast("分享取消")
                }

            })
            .show()
    }

    override fun getStatusLayout(): StatusLayout = mBinding.hlArticleListHint

    override fun onDestroy() {
        super.onDestroy()
        mUserArticleAdapter.removeLoadStateListener(loadStateListener)
    }

    companion object {
        @JvmStatic
        fun newInstance(userId: String): UserArticleListFragment {
            val fragment = UserArticleListFragment()
            val args = Bundle().apply {
                putString(IntentKey.ID, userId)
            }
            fragment.arguments = args
            return fragment
        }
    }
}